package com.asman.vr.utils

import android.content.Context
import android.graphics.Bitmap
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXImageObject
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory


class WXSdk {
    companion object {
        final val APP_ID = "wxf40c905b64fce80f"
    }

    private lateinit var api: IWXAPI

    fun regToWx(context: Context) {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(context, APP_ID, true)

        // 将应用的appId注册到微信
        api.registerApp(APP_ID)

        /*//建议动态监听微信启动广播进行注册到微信
        registerReceiver(object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {

                // 将该app注册到微信
                api.registerApp(APP_ID)
            }
        }, IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP))*/
    }

    fun shareImg(bmp: Bitmap) {
        //初始化 WXImageObject 和 WXMediaMessage 对象
        //初始化 WXImageObject 和 WXMediaMessage 对象
        val imgObj = WXImageObject(bmp)
        val msg = WXMediaMessage()
        msg.mediaObject = imgObj

        //设置缩略图
        /*val thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true)
        bmp.recycle()
        msg.thumbData = Util.bmpToByteArray(thumbBmp, true)*/


        //构造一个Req
        val req = SendMessageToWX.Req()
        // req.transaction = buildTransaction("img")
        req.message = msg
        req.scene = SendMessageToWX.Req.WXSceneSession
        // req.userOpenId = getOpenId()

        //调用api接口，发送数据到微信
        api.sendReq(req)
    }

    fun shareToWXMin(
            webpageUrl: String,
            path: String,
            thumbData: ByteArray,
            title: String,
            description: String
    ) {
        val miniProgramObj = WXMiniProgramObject()
        miniProgramObj.webpageUrl = webpageUrl // 兼容低版本的网页链接

        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE // 正式版:0，测试版:1，体验版:2

        miniProgramObj.userName = "gh_9145107aebe1" // 小程序原始id

        miniProgramObj.path = path //小程序页面路径；对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"

        val msg = WXMediaMessage(miniProgramObj)
        msg.title = title // 小程序消息title

        msg.description = description // 小程序消息desc

        msg.thumbData = thumbData // 小程序消息封面图片，小于128k


        val req = SendMessageToWX.Req()
        // req.transaction = buildTransaction("miniProgram")
        req.message = msg
        req.scene = SendMessageToWX.Req.WXSceneSession // 目前只支持会话

        api.sendReq(req)
    }
}